<?php

define('IN_FIRADIO', TRUE);

function init() {
    $path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    if ($GLOBALS['config']['pagemode'] === 'iframe') {
        $GLOBALS['config']['auto_to_index'] = FALSE;
    }
    if (empty($GLOBALS['config']['auto_to_index']) && substr($path, -1) === '/') {
        $path .= 'index.' . $GLOBALS['config']['PageFileExt'];
    }
    $i = strrpos($path, '.');
    if ($i !== FALSE) {
        // 如果存在扩展名，就去掉
        $path = substr($path, 0, $i);
    }
    // 安全过滤
    $path = str_replace('.', '', $path);
    $path = str_replace('\\', '/', $path);
    $path = trim($path, '/');
    if ($path === '') {
        $path = 'index';
    }
    if (!preg_match('/^[a-z\d\/\-]+$/', $path)) {
        header('HTTP/1.1 403 Forbidden');
        exit('<h1>您输入的路径格式错误</h1>');
    }
    $GLOBALS['config']['paths'] = explode('/', $path);
    // 取根文件名
    $filename = $GLOBALS['config']['paths'][0];
    if (!empty($GLOBALS['config']['auto_to_index']) && count($GLOBALS['config']['paths']) === 1) {
        header('Location: /' . $filename . '/index' . $GLOBALS['config']['PageFileExt']);
    }
    if (isset($GLOBALS['config']['page'])) {
        if (isset($GLOBALS['config']['page'][$filename])) {
            $o = $GLOBALS['config']['page'][$filename];
            if (is_callable($o)) {
                call_user_func($o);
                exit;
            }
        }
    }
    define('DS', DIRECTORY_SEPARATOR);
    $GLOBALS['pagedir'] = __DIR__ . DS . 'page';
    $file = $GLOBALS['pagedir'] . DS . $filename . '.php';
    if (is_file($file)) {
        ob_start();
        include $file;
        $contents = ob_get_contents();
        ob_end_clean();
        $outfile = __WWWROOT__ . DS . str_replace('/', DS, $path) . $GLOBALS['config']['PageFileExt'];
        $outdir = dirname($outfile);
        if (!is_dir($outdir)) {
            @mkdir($outdir);
        }
        if (!is_dir($outdir)) {
            exit('<h1>400页面无效</h1>');
        }
        file_put_contents($outfile, $contents);
        exit($contents);
    }
    //echo $_SERVER['REMOTE_ADDR'];
    exit('<h1>404页面未找到</h1>');
}
